<template>
  <div>
    <!-- nav -->
    <div class="nav">
      <h1>盐城市卫生监督所空气质量在线监测系统</h1>
      <div class="showTime">当前时间：{{ currentTime }}</div>
      <div class="headright" v-if="!$store.state.token">
        <div class="user">
          <div class="userInfo">
            <div class="text">
              <!-- <p class="logout" @click="loginOpen = true">登录</p> -->
            </div>
          </div>
        </div>
      </div>
      <div class="headright" v-if="$store.state.token">
        <img src="../assets/images/usericon.png" alt="" />
        <span class="user1" v-if="$store.state.user">{{ $store.state.user.real_name }}</span>
        <!-- <span class="logout1" @click="logout">注销</span> -->
      </div>
    </div>
    <!-- 登录 -->
    <!-- <div class="masker" v-if="!$store.state.token">
      <div class="popwindow">
        <i class="el-icon-circle-close closeIcon" @click="loginOpen = false"></i>
        <h3>欢迎使用盐城环境监测系统</h3>

        <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="0px" class="login_form">
          用户名
          <el-form-item prop="mobile">
            <div class="flexcontent">
              <div class="inputbox">
                <el-input
                  v-model="loginForm.mobile"
                  prefix-icon="iconfont icon-user"
                  @keyup.enter.native="keyDown()"
                ></el-input>
              </div>
            </div>
          </el-form-item>
          密码
          <el-form-item prop="password">
            <div class="flexcontent">
              <div class="inputbox">
                <el-input
                  v-model="loginForm.password"
                  prefix-icon="iconfont icon-tianchongxing-"
                  type="password"
                  @keyup.enter.native="keyDown()"
                ></el-input>
              </div>
            </div>
          </el-form-item>
          验证码
          <el-form-item class="testcode" :error="codeErr">
            <div class="flexcontent">
              <div class="inputbox">
                <el-input
                  class="inputTest"
                  prefix-icon="iconfont icon-yanzhengma"
                  type="text"
                  name="code"
                  maxlength="4"
                  v-model="code"
                  placeholder="请输入验证码"
                  @blur="testCode"
                  @keyup.enter.native="keyDown()"
                />
              </div>
              <div class="code" @click="getCode">{{ codeNum }}</div>
            </div>
          </el-form-item>
          <el-form-item class="testcode">
            <el-button class="loginBtn" :loading="loading" @click.native.prevent="handleLogin">登 录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div> -->
  </div>
</template>

<script>
import { Login } from '@/utils/api'
export default {
  data() {
    let validatePhone = (rule, value, callback) => {
      const reg = /^1[3-9]\d{9}$/
      if (value === '') {
        callback(new Error('手机号不能为空'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    return {
      currentTime: this.getTime(),
      loginForm: {
        mobile: '',
        password: 'a1234567'
      },
      //这是表单的验证规则
      loginFormRules: {
        //验证用户名是否合法
        mobile: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        //验证密码是否合法
        password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }]
      },
      codeErr: undefined,
      code: undefined,
      codeNum: '',
      loading: false,
      loginOpen: false,
      dialogVisible: false,
      phones: ['18500000099', '18500000050', '18500000051', '18500000052', '18500000053', '18500000054', '18500000055']
      /* 
    盐城总大屏    18500000099    a123456
    ycjc1大润发(盐南店)                             18500000050
    2永辉超市(中南盐城大有境店)                         18500000051
    3爱圣堡激光巨幕主题影院                            18500000052
    4幸福蓝海国际影城(聚龙湖店)                          18500000053
    5横店影视股份有限公司盐城第二分公司                 18500000054
    6盐城幸福蓝海新龙影院管理有限公司                   18500000055 */
    }
  },
  watch: {
    '$route.params.id': {
      handler(val) {
        if (!val) {
          val = 0
        }
        this.loginForm.mobile = this.phones[val]
        window.localStorage.removeItem('token')
        window.localStorage.removeItem('user')
        this.handleLogin()
      },
      immediate: true
    }
  },
  created() {
    // window.localStorage.removeItem('token')
    // window.localStorage.removeItem('user')
    // let id = this.$route.params.id
    // this.loginForm.mobile = this.phones[id]
    // this.handleLogin()
    setInterval(() => {
      this.currentTime = this.getTime()
    }, 1000)
    this.getCode()
  },
  methods: {
    async logout() {
      const confirmResult = await this.$confirm('您确定要退出应用程序吗? 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      //如果用户确认删除，则返回值为字符串 confirm
      //如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return
      }
      this.$store.dispatch('changeToken', '')
      this.$store.dispatch('updateUser', null)
      this.code = undefined
    },
    keyDown() {
      this.handleLogin()
      // 回车则执行登录方法 enter键的ASCII是13
      // if (e.keyCode == 13 || e.keyCode == 100) {
      //   this.handleLogin() // 定义的登录方法
      // }
    },
    getTime() {
      const now = new Date()
      const year = now.getFullYear()
      const month = this.padNumber(now.getMonth() + 1) // 月份是从0开始的
      const day = this.padNumber(now.getDate())
      const hours = this.padNumber(now.getHours())
      const minutes = this.padNumber(now.getMinutes())
      const seconds = this.padNumber(now.getSeconds())
      return year + '年' + month + '月' + day + '日' + ' ' + hours + ':' + minutes + ':' + seconds
    },
    padNumber(num) {
      return num < 10 ? '0' + num : num
    },
    getCode() {
      this.codeNum = ''
      for (var i = 0; i < 4; i++) {
        this.codeNum += Math.floor(Math.random() * 10)
      }
    },
    testCode() {
      if (this.code == this.codeNum) {
        this.codeErr = ''
      } else {
        this.codeErr = '请输入正确的验证码'
      }
    },
    async handleLogin() {
      // if (this.loading) return
      // this.testCode()
      // if (this.codeErr) {
      //   return
      // }
      // this.$refs.loginFormRef.validate(async (valid) => {
      //   if (!valid) return
      const {
        data: { mobile, real_name, token }
      } = await Login({ ...this.loginForm })
      this.$store.dispatch('changeToken', token)
      this.$store.dispatch('updateUser', { mobile, real_name })
      // this.$refs.loginFormRef.resetFields()
      this.getCode()
      this.$emit('initData')
      // this.innitData()
      // })
    }
  }
}
</script>

<style>
</style>